//app.js

App({
  globalData: { 
    //address: 'http://p87v3s.natappfree.cc/diTui_wxapp/',
    address: 'https://mp.yingdao8.com/diTui_wxapp/',
    socketPath: 'wss://mp.yingdao8.com/',
    path:'https://mp.yingdao8.com/',
    //path: 'https://mp.yingdao8.com/',
    weChatInfo: null,//用户微信信息
    userInfo: null,//数据库中的用户信息
    sessionId: null,//请求的sessionId
    APPID:null,
    APPSECRET:null,
    phone:null,
    indexNeedReload:false,//刷新首页名片
  },
  onLaunch: function () {
    var that = this;
    // 展示本地存储能力
    var logs = wx.getStorageSync('logs') || []
    logs.unshift(Date.now())
    wx.setStorageSync('logs', logs)   

    var ext = wx.getExtConfigSync();
    console.log(ext)
    that.globalData.APPID = ext.appid;
    wx.setStorageSync('companyId',ext.companyId);
    that.globalData.phone = wx.getStorageSync('phone')
   
   
    // console.log('企业ID:' + wx.getStorageSync('companyId'))
    // if (that.globalData.sessionId){
    //   console.log('session存在')
    //   that.refresh();
    // }else{
    //   console.log('sessionid过期')
    //   that.getSession();
    // }
  },
  refresh:function(){
    var that = this;
    //setInterval(that.getSession(),15*60*1000);
  },
  

  getSession:function(cb){
    var that = this;
    var user = that.globalData.weChatInfo;
    // if (user.nickName == undefined || that.globalData.sessionId!=null) {
    //   typeof cb == "function" && cb(that.globalData.weChatInfo);
    //   // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
    //   // 所以此处加入 callback 以防止这种情况
    //   if (that.userInfoReadyCallback) {
    //     that.userInfoReadyCallback(res)
    //   }
    //   return;
    // }
    // console.log(user)
    wx.request({
      url: that.globalData.address + 'User/saveUserToSession',
      data: {
        appid: that.globalData.APPID,
        openid: wx.getStorageSync('openId'),
        screenname: user.nickName,
        sex: user.gender,
        language: user.language,
        city: user.city,
        province: user.province,
        state: user.country,
        headaddress: user.avatarUrl
      },
      method: 'POST',
      header: {
        'content-type': 'application/x-www-form-urlencoded' // 默认值 
      },
      success: function (result) {
       
        if (result.data != '0') {
          that.globalData.sessionId = result.data;
          // console.log('新sessionid：' + that.globalData.sessionId) 
          typeof cb == "function" && cb(that.globalData.weChatInfo);
          // 由于 getUserInfo 是网络请求，可能会在 Page.onLoad 之后才返回
          // 所以此处加入 callback 以防止这种情况
          if (that.userInfoReadyCallback) {
            that.userInfoReadyCallback(res)
          }
        }
      }
    })
  },

  getUserInfo:function(cb){
    var that = this;
    if (that.globalData.weChatInfo) {
      that.getSession(cb); 
    } else {
      // 登录
      wx.login({
        success: res => {
          // 发送 res.code 到后台换取 openId, sessionKey, unionId
          console.log(res)
          console.log(that.globalData.path+'diTui_cbManagement/miniprogramApp/login');
          // if (wx.getExtConfig) {
          //   wx.getExtConfig({
          //     success: function (res) {
          //       console.log(res.extConfig)
          //     }
          //   })
          // }
        
          //获取openid
          wx.request({
            //获取openid接口
            url: that.globalData.path +'diTui_cbManagement/miniprogramApp/login',
            data: {
              appid: that.globalData.APPID,
              code: res.code
            },
            header: {
              'content-type': 'application/x-www-form-urlencoded' // 默认值 
            },
            method: 'POST',
            success: function (res) {
              console.log(res)
              let openId = res.data.openid;
              let sessionkey = res.data.session_key;
              wx.setStorageSync('openId', openId);
              wx.setStorageSync('sessionKey', sessionkey);
              //  检查是否登录
              // 查看是否授权
              wx.getSetting({
                success: function (res) {
                  if (res.authSetting['scope.userInfo']) {
                    // 已经授权，可以直接调用 getUserInfo 获取头像昵称
                    wx.getUserInfo({
                      success: function (res) {
                        console.log('授权登录成功')
                        wx.setStorageSync('weChatInfo', res.userInfo)
                        that.globalData.weChatInfo = res.userInfo; 
                        that.getSession(cb); 
                      }
                    })
                  } else {
                    console.log('获取失败')
                    wx.redirectTo({
                      url: '/pages/index/subPackages/authorization/authorization',
                    })
                  }
                }
              })
            }
          })

          // wx.request({
          //   url: 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=' + APPID + '&secret=' + APPSECRET,
          //   success: function (res) {
          //     console.log(res.data)
          //   }
          // })
        }
      })
    }
  }
})

